<template>
    <el-dialog v-model="dialogVisible" title="编辑个人资料" width="600px" :before-close="handleClose">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="left">
            <!-- 基本信息 -->
            <el-form-item label="昵称" prop="nickname">
                <el-input v-model="form.nickname" placeholder="请输入昵称" maxlength="20" show-word-limit />
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入手机号" maxlength="11" />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" type="email" />
            </el-form-item>

            <!-- 个人简介 -->
            <el-form-item label="个人简介" prop="bio">
                <el-input v-model="form.bio" type="textarea" :rows="3" placeholder="介绍一下自己吧～" maxlength="200"
                    show-word-limit />
            </el-form-item>

            <!-- 职业信息 -->
            <el-form-item label="所在城市" prop="city">
                <el-input v-model="form.city" placeholder="请输入所在城市" />
            </el-form-item>

            <el-form-item label="公司" prop="company">
                <el-input v-model="form.company" placeholder="请输入公司名称" />
            </el-form-item>

            <el-form-item label="职位" prop="position">
                <el-input v-model="form.position" placeholder="请输入职位" />
            </el-form-item>

            <!-- 个人信息 -->
            <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="form.gender">
                    <el-radio :label="0">未知</el-radio>
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="2">女</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入详细地址" />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="loading">
                保存
            </el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { validatePhone, validateEmail } from '@/utils/validate'

const userStore = useUserStore()

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    userInfo: {
        type: Object,
        default: () => ({})
    }
})

const emit = defineEmits(['update:modelValue', 'success'])

const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
    nickname: '',
    phone: '',
    email: '',
    bio: '',
    city: '',
    company: '',
    position: '',
    gender: 0,
    address: ''
})

// 自定义验证规则
const validatePhoneRule = (rule, value, callback) => {
    if (!value) {
        callback()
    } else if (!validatePhone(value)) {
        callback(new Error('请输入正确的手机号'))
    } else {
        callback()
    }
}

const validateEmailRule = (rule, value, callback) => {
    if (!value) {
        callback()
    } else if (!validateEmail(value)) {
        callback(new Error('请输入正确的邮箱格式'))
    } else {
        callback()
    }
}

// 验证规则
const rules = {
    nickname: [
        { required: false, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
        { required: false, message: '请输入手机号', trigger: 'blur' },
        { validator: validatePhoneRule, trigger: 'blur' }
    ],
    email: [
        { required: false, message: '请输入邮箱', trigger: 'blur' },
        { validator: validateEmailRule, trigger: 'blur' }
    ],
    bio: [
        { max: 200, message: '个人简介不能超过 200 个字符', trigger: 'blur' }
    ]
}



// 监听显示状态
watch(() => props.modelValue, (val) => {
    dialogVisible.value = val
    if (val) {
        initForm()
    }
})

// 监听对话框状态
watch(dialogVisible, (val) => {
    emit('update:modelValue', val)
})

// 初始化表单数据
const initForm = () => {
    Object.keys(form).forEach(key => {
        form[key] = props.userInfo[key] || ''
    })
    // 确保性别有默认值
    if (props.userInfo.gender === undefined || props.userInfo.gender === null) {
        form.gender = 0
    } else {
        form.gender = props.userInfo.gender
    }
}

// 关闭对话框
const handleClose = () => {
    dialogVisible.value = false
}

// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()
        loading.value = true

        // 过滤空值
        const submitData = Object.keys(form).reduce((acc, key) => {
            if (form[key] !== null && form[key] !== undefined && form[key] !== '') {
                acc[key] = form[key]
            }
            return acc
        }, {})

        const response = await userStore.updateUserInfo(submitData)
        emit('success')
        handleClose()
    } catch (error) {
        ElMessage.error(error.message || '资料更新失败')
    } finally {
        loading.value = false
    }
}
</script>

<style scoped>
:deep(.el-form-item__label) {
    font-weight: 500;
}
</style>